const {
  dingDongBot,
  getMessagePayload,
  LOGPRE,
  sellingMembership,
  chatGpt,
  writeToTxtFile,
} = require("./helper");
const { log, ScanStatus, WechatyBuilder } = require("wechaty");
const { PuppetPadlocalToken } = require("./configs/botConfig");
const { PuppetPadlocal,botName } = require("wechaty-puppet-padlocal");

/****************************************
 * 去掉注释，可以完全打开调试日志
 ****************************************/
// log.level("silly");

const puppet = new PuppetPadlocal({
  token: PuppetPadlocalToken,
  autoLogin: false, // 设置为不自动登录(没啥用)
  puppetConfig: {
    selfId: null, // 禁止自我消息（貌似也没用 还是代码里判断了）
  },
});

async function runBot() {
  return new Promise((resolve, reject) => {
    const bot = WechatyBuilder.build({
      name: botName,
      puppet,
      autoLogin: false,// 也没用
    });

    bot.start().then(() => {
      log.info(LOGPRE, "机器开始启动.");
    });
    bot
      .on("scan", (qrcode, status) => {
        console.log("qrcode", qrcode);
        console.log("status", status);
        if (status === ScanStatus.Waiting && qrcode) {
          const qrcodeImageUrl = [
            "https://wechaty.js.org/qrcode/",
            encodeURIComponent(qrcode),
          ].join("");
          resolve(qrcode);
          log.info(
            LOGPRE,
            `扫码: ${ScanStatus[status]}(${status}) - ${qrcodeImageUrl}`
          );

          require("qrcode-terminal").generate(qrcode, { small: true });
        } else {
          log.info(LOGPRE, `扫码状态: ${ScanStatus[status]}(${status})`);
        }
      })

      .on("login", (user) => {
        log.info(LOGPRE, `${user} 登录成功`);
      })

      .on("logout", (user, reason) => {
        log.info(LOGPRE, `${user} 登出, 原因: ${reason}`);
      })

      .on("message", async (message) => {
        log.info(LOGPRE, `收到消息: ${message.toString()}`);

        await getMessagePayload(message);

        await dingDongBot(message);

        await sellingMembership(message);

        //await chatGpt(message);
      })

      .on("room-invite", async (roomInvitation) => {
        //处理邀请加入群聊
        log.info(LOGPRE, `on room-invite: ${roomInvitation}`);
      })

      .on("room-join", (room, inviteeList, inviter, date) => {
        //当有新成员加入一个群聊时，Wechaty会触发room-join事件
        log.info(
          LOGPRE,
          `新成员加入群聊, room:${room}, inviteeList:${inviteeList}, inviter:${inviter}, date:${date}`
        );
      })

      .on("room-leave", (room, leaverList, remover, date) => {
        //当有成员离开一个群聊时，Wechaty会触发room-leave事件
        log.info(
          LOGPRE,
          `有成员离开群聊, room:${room}, leaverList:${leaverList}, remover:${remover}, date:${date}`
        );
      })

      .on("room-topic", (room, newTopic, oldTopic, changer, date) => {
        //当一个群聊的名称发生变更时
        log.info(
          LOGPRE,
          `群聊的名称发生变更, room:${room}, newTopic:${newTopic}, oldTopic:${oldTopic}, changer:${changer}, date:${date}`
        );
      })

      .on("friendship", async (friendship) => {
        //friendship事件用于处理好友添加请求和确认的事件
        log.info(LOGPRE, `on friendship: ${friendship}`);
        /* if (friendship.type() === bot.Friendship.Type.Receive) {
        // 收到好友添加请求
        await friendship.accept();
        console.log(`接受了来自 ${friendship.contact().name()} 的好友添加请求`);
      } else if (friendship.type() === bot.Friendship.Type.Confirm) {
        // 好友添加请求已确认
        console.log(`已成为好友：${friendship.contact().name()}`);
      } */
      })
      .on("ready", async () => {
        console.log("Wechaty bot is ready");

        // 根据微信号查找联系人
        const contact = await bot.Contact.find({ alias: "xx" }); // 替换为你要发送消息的好友微信号
        console.log(contact, "contact");
        if (contact) {
          await contact.say("这是通过微信号发送的消息！");
          console.log("消息发送成功");
        } else {
          console.log("未找到指定的联系人");
        }
      })
      .on("error", (error) => {
        log.error(LOGPRE, `程序产生错误: ${error}`);
      });
    console.log(bot.logonoff(), "-----bot.logonoff()");

    // 监听 SIGINT 信号（Ctrl+C）
    process.on("SIGINT", async () => {
      console.info("接收到 SIGINT 信号");
      // 执行关闭实例的操作
      await bot.stop();
      process.exit(0);
    });

    // 监听 SIGTERM 信号
    process.on("SIGTERM", async () => {
      console.info("接收到 SIGTERM 信号");
      // 执行关闭实例的操作
      await bot.stop();
      process.exit(0);
    });
  });
}

module.exports = {
  runBot,
};
